package com.franklin.ideaplugin.mybatisrunner.utils;

import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.mybatisrunner.entity.ElExpression;
import com.google.common.collect.Lists;
import com.intellij.psi.PsiElement;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlText;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.io.StringReader;
import java.util.List;

/**
 * @author Ye Junhui
 * @since 2024/2/20
 */
public class XmlUtils {

    /**
     * 寻找子元素
     * @param xmlTag
     * @return
     */
    public static List<XmlElement> findXmlChild(@NotNull XmlTag xmlTag){
        List<XmlElement> xmlElementList = Lists.newArrayList();
        for (PsiElement psiElement : xmlTag.getChildren()) {
            if (psiElement instanceof XmlText || psiElement instanceof XmlTag){
                xmlElementList.add((XmlElement) psiElement);
            }
        }
        return xmlElementList;
    }

    /**
     * 获取属性
     * @param xmlTag
     * @param attributeName
     * @return
     */
    public static String getAttributeValue(@NotNull XmlTag xmlTag,String attributeName){
        return StrUtil.blankToDefault(xmlTag.getAttributeValue(attributeName),"");
    }

    /**
     * 寻找El表达式
     * @param xmlText
     * @return
     */
    public static List<ElExpression> findElExpressionList(XmlText xmlText) {
        List<ElExpression> result = Lists.newArrayList();
        String target = xmlText.getValue();
        for (int i = 0; i < target.length(); i++) {
            char c = target.charAt(i);
            if (c == '#' || c == '$') {
                int j = i + 1;
                boolean isEl = true;
                while (j < target.length() && target.charAt(j) != '{') {
                    if (target.charAt(j) == ' ') {
                        j++;
                    } else {
                        isEl = false;
                        break;
                    }
                }
                if (isEl) {
                    while (j < target.length() && target.charAt(j) != '}') {
                        j++;
                    }
                    //表达式
                    String expression = StringUtils.deleteWhitespace(target.substring(i, j + 1));
                    //psi元素
                    PsiElement psiElement = xmlText.findElementAt(i);

                    ElExpression elExpression = new ElExpression();
                    elExpression.setExpression(expression);
                    elExpression.setPsiElement(psiElement);

                    result.add(elExpression);
                    i = j + 1;
                }
            }
        }
        return result;
    }
}
